package com.nidu.demo.mail.executor.command;

import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.BizException;
import com.nidu.demo.mail.convertor.MailAccountConvertor;
import com.nidu.demo.mail.dto.MailAccountUpdateCmd;
import com.nidu.demo.mail.dto.MailAccountCO;
import com.nidu.demo.mail.gateway.MailAccountGateway;
import com.nidu.demo.mail.model.MailAccount;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 邮件账号更新命令执行器
 *
 * @author auto
 */
@Component
@RequiredArgsConstructor
public class MailAccountUpdateCmdExe {

    private final MailAccountConvertor convertor;
    private final MailAccountGateway gateway;

    @Transactional
    public SingleResponse<MailAccountCO> execute(MailAccountUpdateCmd cmd) {
        // 1. 转换为领域对象
        MailAccount mailAccount = MailAccount.update(cmd.getId(), cmd.getMail(), cmd.getUsername(), cmd.getPassword(), cmd.getHost(),
                cmd.getPort(), cmd.getSslEnable(), cmd.getStarttlsEnable());

        // 2. 保存邮件账号
        MailAccount saved = gateway.create(mailAccount);

        // 3. 转换为DTO返回
        MailAccountCO mailAccountCO = convertor.toClientObject(saved);
        return SingleResponse.of(mailAccountCO);
    }

}
